//
//  HYPhotoVideoViewModel.m
//  XPlayer
//
//  Created by liguoqing on 2023/8/5.
//

#import "HYPhotoVideoViewModel.h"
#import "HYHomeFolderModel.h"
#import "HYPhotoVideoItemViewModel.h"
#import <Photos/Photos.h>
#import "HYVideoModel.h"
#import "HYHomeVideoModel.h"
#import <HYUtls/CommUtls+Time.h>
#import <HYVideoPlayer/HYVideoPlayerConfig.h>

@interface HYPhotoVideoViewModel ()
/// 相册文件夹
@property (nonatomic, strong) HYHomeFolderModel *folderModel;
/// 视频播放数据
@property (nonatomic, strong) NSMutableArray *videoArray;
/// 相册视频
@property (nonatomic, strong) NSMutableArray *photoVideoArray;
/// 选中视频数据
@property (nonatomic, strong) NSMutableArray *selectVideoArray;
/// icloudSync同步中
@property (nonatomic, assign) NSInteger isCloudSync;

@end

@implementation HYPhotoVideoViewModel

- (instancetype)init
{
    self = [super init];
    if(self){
        self.saveSuccessSubject = [RACSubject subject];
        self.syncSubject = [RACSubject subject];
    }
    return self;
}

- (void)fetchPhotoVideoAuthAndSources
{
    if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized){
        [self fetchPhotoVideoData];
    }else{
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if(status == PHAuthorizationStatusAuthorized){
                [self fetchPhotoVideoData];
            }
        }];
    }
}

- (void)fetchPhotoVideoData
{
   PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
   for (PHAssetCollection *collection in smartAlbums) {
       PHFetchResult *results = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
       if(!results.count){
           [self.updatedContentSignal sendNext:@[]];
           return;
       }
       @weakify(self);
       // 图片
       PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
       options.synchronous = YES;
//        options.resizeMode = PHImageRequestOptionsResizeModeExact;
       options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
       self.isCloudSync = results.count;
       for (NSInteger i = 0; i < results.count; i ++) {
           PHAsset *asset = results[i];
           [[PHImageManager defaultManager]requestImageForAsset:asset targetSize:CGSizeMake(300, 300) contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
               @strongify(self);
               HYPhotoVideoItemViewModel *photoModel = [[HYPhotoVideoItemViewModel alloc]init];
               photoModel.maxBlock = ^BOOL{
                   @strongify(self);
                   return self.selectCount>=self.maxSelectCount;
               };
               [self rac_liftSelector:@selector(selectVideo:)withSignals:[photoModel.selectSubject map:^id(id value) {
                   return photoModel;
               }], nil];
               photoModel.videoImage = image;
               photoModel.videoDuration = [CommUtls timeToMS:asset.duration];
               photoModel.createDate = [CommUtls encodeTimeYearMonthDay:asset.creationDate];
               HYVideoModel *videoModel = [[HYVideoModel alloc]init];
               videoModel.videoImage = image;
               videoModel.videoDuration = [CommUtls timeToMS:asset.duration];
               videoModel.createDate = [CommUtls encodeTimeYearMonthDay:asset.creationDate];
               [self requestPlayerItemForVideoWithAsset:asset videoModel:videoModel photoModel:photoModel];
               [self.videoArray insertObject:videoModel atIndex:0];
               [self.photoVideoArray insertObject:photoModel atIndex:0];
           }];
       }
       dispatch_async(dispatch_get_main_queue(), ^{
           [self.updatedContentSignal sendNext:self.photoVideoArray];
       });
   }
}

- (void)requestPlayerItemForVideoWithAsset:(PHAsset *)asset
                                videoModel:(HYVideoModel *)videoModel
                                photoModel:(HYPhotoVideoItemViewModel *)photoModel
{
    PHVideoRequestOptions* videoOption = [[PHVideoRequestOptions alloc] init];
    videoOption.version = PHVideoRequestOptionsVersionOriginal;
    videoOption.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    videoOption.networkAccessAllowed = YES;
    @weakify(self);
    [[PHCachingImageManager defaultManager] requestPlayerItemForVideo:asset options:videoOption resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
        @strongify(self);
        NSString *videoUrl = [(AVURLAsset *)playerItem.asset URL].absoluteString;
        photoModel.videoUrl = videoUrl;
        videoModel.videoUrl = videoUrl;
        NSString *videoTitle;
        if([videoUrl containsString:@"file://"]){//本地文件
            videoTitle = [videoUrl lastPathComponent];
            photoModel.isLocalVideo = YES;
        }else{
            NSString *videoUrlStr = [videoUrl componentsSeparatedByString:@"?"].firstObject;
            videoTitle = [videoUrlStr lastPathComponent];
            photoModel.isLocalVideo = NO;
        }
        photoModel.videoTitle = videoTitle;
        videoModel.videoTitle = videoTitle;
        NSString *firstName = [CommUtls fetchVideoNameWithFullName:videoTitle];
        NSString *imageName = [NSString stringWithFormat:@"%@.png",firstName];
        videoModel.videoImagePath = imageName;
        CLog(@"videoUrl -- %@",videoModel.videoUrl);
        if(videoModel.videoUrl.length){
            self.isCloudSync --;
            if(!self.isCloudSync){
                [self.syncSubject sendNext:nil];
            }
        }
    }];
}

- (NSInteger)numberOfRowsInSection
{
    return self.photoVideoArray.count;
}

- (id)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.photoVideoArray[indexPath.row];
}

- (BOOL)isCanPlay:(NSIndexPath *)indexPath
{
    // 无网络播放本地视频
    if([HYNetWorkManager shareManager].currentReachabilityStatus == NotReachable && self.isCloudSync){
        HYVideoModel *currentModel = self.videoArray[indexPath.row];
        if(currentModel.videoUrl.length){
            return YES;
        }
        return NO;
    }
    return !self.isCloudSync;
}

- (HYVideoViewModel *)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HYVideoPlayerConfig *config = [self fetchVideoConfigAtIndexPath:indexPath];
    HYVideoViewModel *viewModel = [[HYVideoViewModel alloc]initWithFolderIdentification:self.folderModel.folderIdentification
                                                                              isPrivate:self.folderModel.isLock
                                                                            videoConfig:config];
    return viewModel;
}

- (HYVideoPlayerConfig *)fetchVideoConfigAtIndexPath:(NSIndexPath *)indexPath
{
    HYVideoModel *currentModel = self.videoArray[indexPath.row];
    currentModel.isSelect = YES;
    HYVideoPlayerConfig *config = [HYVideoPlayerConfig new];
    config.isBasePlayer = YES;
    config.currentVideoModel = currentModel;
    if([HYNetWorkManager shareManager].currentReachabilityStatus == NotReachable && self.isCloudSync){
        config.videoSoucres = @[currentModel];
    }else{
        config.videoSoucres = self.videoArray;
    }
    config.isSupportProjectionScreen = NO;
    return config;
}

- (void)selectVideo:(HYPhotoVideoItemViewModel *)itemViewModel
{
    if(itemViewModel.isSelect){
        [self.selectVideoArray addObject:itemViewModel];
    }else{
        [self.selectVideoArray removeObject:itemViewModel];
    }
    self.selectCount = self.selectVideoArray.count;
}

- (void)saveSelectPhotoVideo
{
    __block NSInteger importCount = self.selectVideoArray.count;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self.selectVideoArray enumerateObjectsUsingBlock:^(HYPhotoVideoItemViewModel *itemViewModel, NSUInteger idx, BOOL * _Nonnull stop) {
            // 判断该视频在当前文件夹下是否存在，如果存在则不需要重复保存
            NSArray *results = [HYHomeVideoModel searchWithSQL:[NSString stringWithFormat:@"select * from VIDEOLIST where videoTitle = '%@' and folderIdentification = '%@'",itemViewModel.videoTitle,self.folderIdentification]];
            BOOL isExist =  results.count;
            if(!isExist){
                NSString *firstName = [CommUtls fetchVideoNameWithFullName:itemViewModel.videoTitle];
                NSString *imageName = [NSString stringWithFormat:@"%@.png",firstName];
                NSString *imagePath = [HYFileManager videoImageSavePathWithFileName:imageName];
                BOOL isSaveImage;
                if([kFileManager fileExistsAtPath:imagePath]){// 判断视频封面本地沙盒是否存在
                    isSaveImage = YES;
                }else{
                    NSData *imageData = UIImagePNGRepresentation(itemViewModel.videoImage);
                    isSaveImage = [imageData writeToFile:imagePath atomically:YES];
                }
                if(isSaveImage){
                    if(itemViewModel.isLocalVideo){
                        NSString *saveVideoPath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:itemViewModel.videoTitle];
                        BOOL isSaveVideo;
                        if([kFileManager fileExistsAtPath:saveVideoPath]){// 判断视频是否保存过
                            isSaveVideo = YES;
                        }else{
                            NSData *videoData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:itemViewModel.videoUrl]];
                            isSaveVideo = [videoData writeToFile:saveVideoPath atomically:YES];
                        }
                        if(isSaveVideo){
                            [self addPhotoVideoToDBWithItemViewModel:itemViewModel videoImageName:imageName];
                        }
                    }else{
                        [self addPhotoVideoToDBWithItemViewModel:itemViewModel videoImageName:imageName];
                    }
                }
            }
            importCount --;
            if(!importCount){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.saveSuccessSubject sendNext:nil];
                });
            }
        }];
    });
}

// 添加到视频列表库中
- (BOOL)addPhotoVideoToDBWithItemViewModel:(HYPhotoVideoItemViewModel *)itemViewModel videoImageName:(NSString *)videoImageName;
{
    HYHomeVideoModel *videoModel = [[HYHomeVideoModel alloc]init];
    videoModel.videoTitle = itemViewModel.videoTitle;
    videoModel.folderIdentification = self.folderIdentification;
    videoModel.imageName = videoImageName;
    videoModel.isLocal = itemViewModel.isLocalVideo;
    if(!itemViewModel.isLocalVideo){
        videoModel.videoUrl = itemViewModel.videoUrl;
    }
    videoModel.videoDuration = itemViewModel.videoDuration;
    videoModel.createDate = itemViewModel.createDate;
    videoModel.importDate = [CommUtls encodeTimeYearMonthDay:[NSDate date]];
    videoModel.isSuperPrivate = self.isSuperPrivate;
    BOOL isSave = [videoModel saveToDB];
    if(isSave){
        dispatch_async(dispatch_get_main_queue(), ^{
            [kNotificationCenter postNotificationName:kAddNewVideoNotification object:@{@"videoModel":videoModel,@"folderIdentification":self.folderIdentification}];
        });
    }else{
        [HYHub showMessage:NSLocalizedString(@"视频导入失败", nil)];
    }
    return isSave;
}

- (void)cancelSelectPhotoVideo
{
    if(self.selectVideoArray.count){
        [self.selectVideoArray enumerateObjectsUsingBlock:^(HYPhotoVideoItemViewModel *itemViewModel, NSUInteger idx, BOOL * _Nonnull stop) {
            itemViewModel.isSelect = NO;
        }];
        [self.selectVideoArray removeAllObjects];
        self.selectCount = 0;
        [self.updatedContentSignal sendNext:self.photoVideoArray];
    }
}

#pragma mark - loadLazy
- (NSMutableArray *)photoVideoArray
{
    if(!_photoVideoArray){
        _photoVideoArray = [NSMutableArray array];
    }
    return _photoVideoArray;
}

- (NSMutableArray *)videoArray
{
    if(!_videoArray){
        _videoArray = [NSMutableArray array];
    }
    return _videoArray;
}

- (NSMutableArray *)selectVideoArray
{
    if(!_selectVideoArray){
        _selectVideoArray = [NSMutableArray array];
    }
    return _selectVideoArray;
}

- (HYHomeFolderModel *)folderModel
{
    if(!_folderModel){
        NSString *sql = [NSString stringWithFormat:@"select * from FOLDERLIST where folderType = '%ld'",HYHomeFolderType_Photo];
        _folderModel = [HYHomeFolderModel searchWithSQL:sql].firstObject;
    }
    return _folderModel;
}

@end
